package com.project.dao.impl;

import com.project.bean.UserBean;
import com.project.dao.IUserDao;

import java.sql.SQLException;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;

public class UserDaoImpl extends BaseDao implements IUserDao {
    @Override
    public UserBean login(String userName, String pwd) {
        UserBean user = null;
        this.setConnection();
        try {
            ps = con.prepareStatement("select * from t_user where u_name=? and u_pwd=?");
            ps.setObject(1,userName);
            ps.setObject(2,pwd);

            rs = ps.executeQuery();
            if(rs.next()){
                user = this.getUser();
            }

        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally{
            this.closeConnection();
        }

        return user;
    }

    @Override
    public void add(UserBean user) {
        this.setConnection();

        try {
            ps = con.prepareStatement("insert into t_user(u_name,u_pwd,u_birthday,u_phone,u_money) values(?,?,?,?,?)");
            ps.setObject(1,user.getUserName());
            ps.setObject(2,user.getPwd());
            ps.setObject(3,user.getBirthday());
            ps.setObject(4,user.getPhone());
            ps.setObject(5,user.getMoney());

            ps.executeUpdate();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally{
            this.closeConnection();
        }
    }

    @Override
    public List<UserBean> findAll() {
        List<UserBean> list = new ArrayList<>();
        this.setConnection();
        try {
            ps = con.prepareStatement("select * from t_user");
            rs = ps.executeQuery();
            while(rs.next()){
                list.add(this.getUser());
            }

        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally{
            this.closeConnection();
        }

        return list;
    }

    public UserBean getUser() throws SQLException{
        UserBean user = new UserBean();
        user.setId(rs.getInt("pk_userId"));
        user.setUserName(rs.getString("u_name"));
        user.setPwd(rs.getString("u_pwd"));
        user.setBirthday(LocalDate.parse(rs.getString("u_birthday")));
        user.setPhone(rs.getString("u_phone"));
        user.setMoney(rs.getInt("u_money"));
        return user;
    }
}
